<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>WebSocket Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<!-- <link rel="stylesheet" th:href="@{/css/main.css}" /> -->
<!-- <script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script> -->
<script th:src="@{jquery.js}"></script>

</head>
<body>
your name is:<span th:text="${username}">aaa</span>
<div id="target">
</div>
<input type = "text" id = "to" value="who"/>
<input type = "text" id = "msg" />
	<div>
		<input type="button" id="btn_test" value="Send" />
	</div>
	<div>
		<div id="test_1" style="overflow:auto;border:1px solid black;width:200px;height:200px"></div>
	</div>
</body>
<script type="text/javascript">
	//<![CDATA[ 
	$(document).ready(
			function() {
				
				$('#msg').bind('keypress',function(event){ 
			         
			          
			         if(event.keyCode == 13)      

			         {  
			        	 $('#btn_test').click();
			        	 $('#msg').val(""); 
			         }  

			     });
				
				
				var websocket = null;
				
				    //这个名字库只能自己填充内容了，js没这么智能，可以自己拼个名字出来...
				    var store = ['Marry','Jhon','Tom','Lily','Jerry','Josh','ZhouJ','Super','Persure','Hap','Gosling','Jack','Lucy','Albert'],
				    el = document.getElementById('target');
				    var name = store[Math.floor(Math.random()*store.length)] + Math.floor(Math.random()*1000);
				    el.innerHTML = name;
				// 模拟登陆
				$.post("login?userId=" + name, function(data) {
					// 初始化一个WebSocket连接
					websocket = new WebSocket("ws://192.168.8.228:8080/websocket");
					websocket.onopen = function(event) {
						$("#test_1").empty();
						var label = $("<label>").html("开始执行....");
						$("#test_1").append(label).append("<br>");
					};
					// websocket接收的信息会通过这个回调方法返回给前端
					websocket.onmessage = function(event) {
						onMessage(event);
					};
				})

				// 打印收到的websocket返回信息
				function onMessage(event) {
					$("#test_1").append(
							"<label class='navbar-label'>" + event.data
									+ "</label>").append("</br>");
					$("#test_1").scrollTop($("#test_1")[0].scrollHeight);
				}


				//报错处理回调函数
				function onError(event) {
					alert(event.data);
				}

				//点击页面上的一个按钮，通过一个普通方法来开始一个websocket请求
				$("#btn_test").click(function() {
					
					$("#test_1").append(
							"<label class='navbar-label'>" + $("#target").html()+":" +$("#msg").val() + "</label>").append("</br>");
					$("#test_1").scrollTop($("#test_1")[0].scrollHeight);
					
					var to = $("#to").val();
					$.post("send/message?to=" + to + "&msg=" + $("#target").html() +":"+$("#msg").val(), null, function() {
					})
				})
			})
	//]]>
</script>
</html>